import { IPSAppCodeList, IPSAppDEMultiDataView, IPSCodeItem } from '@ibiz/dynamic-model-api';
import { LogUtil, Util } from '../../../util';
import { AppMDCtrlEvents, IParam, MobSearchFormEvents, IAppDEMultiDataViewController } from '../../../interface';
import { AppDEViewController } from './app-de-view-controller';

/**
 * @description 多数据视图控制器基类
 * @export
 * @class AppDEMultiDataViewController
 * @extends {AppDEViewController}
 * @implements {IAppDEMultiDataViewController}
 */
export class AppDEMultiDataViewController extends AppDEViewController implements IAppDEMultiDataViewController {
  /**
   * @description 多数据视图基类实例对象
   * @type {IPSAppDEMultiDataView}
   * @memberof AppDEMultiDataViewController
   */
  public viewInstance!: IPSAppDEMultiDataView;

  /**
   * @description 是否开启快速分组
   * @type {boolean}
   * @memberof AppDEMultiDataViewController
   */
  public isEnableQuickGroup: boolean = false;

  /**
   * @description 快速分组代码表
   * @type {IPSAppCodeList}
   * @memberof AppDEMultiDataViewController
   */
  public quickGroupCodeList?: IPSAppCodeList;

  /**
   * @description 快速分组是否有抛值
   * @type {boolean}
   * @memberof AppDEMultiDataViewController
   */
  public isEmitQuickGroupValue: boolean = false;

  /**
   * @description 快速分组模型数据
   * @type {Array<IParam>}
   * @memberof AppDEMultiDataViewController
   */
  public quickGroupModel: Array<IParam> = [];

  /**
   * @description 是否为多选
   * @type {boolean}
   * @memberof AppDEMultiDataViewController
   */
  public isMultiple!: boolean;

  /**
   * @description 是否展开搜索表单
   * @type {boolean}
   * @memberof AppDEMultiDataViewController
   */
  public isExpandSearchForm: boolean = false;

  /**
   * @description 快速分组存储参数
   * @type {IParam}
   * @memberof AppDEMultiDataViewController
   */
  public quickGroupParam: IParam = {};

  /**
   * @description 快速搜索参数
   * @type {IParam}
   * @memberof AppDEMultiDataViewController
   */
  public searchParam: IParam = {};

  /**
   * @description 初始化输入数据
   * @param {*} opts
   * @memberof AppDEMultiDataViewController
   */
  public initInputData(opts: any) {
    super.initInputData(opts);
    this.isMultiple = opts.isMultiple;
  }

  /**
   * @description 视图基础数据初始化
   * @memberof AppDEMultiDataViewController
   */
  public viewBasicInit() {
    super.viewBasicInit();
    this.isEnableQuickGroup = this.viewInstance.enableQuickGroup;
    if (this.isEnableQuickGroup) {
      this.quickGroupCodeList = this.viewInstance.getQuickGroupPSCodeList() as IPSAppCodeList;
    }
  }

  /**
   * @description 初始化快速分组
   * @return {*}
   * @memberof AppDEMultiDataViewController
   */
  public async initQuickGroup() {
    if (!this.isEnableQuickGroup || !this.quickGroupCodeList) {
      return;
    }
    await this.quickGroupCodeList.fill(true);
    try {
      const quickGroupItems: any[] = await App.getCodeListService().getDataItems({
        tag: this.quickGroupCodeList.codeName,
        type: this.quickGroupCodeList.codeListType,
        navContext: this.context,
        navViewParam: this.viewParam,
      });
      this.quickGroupModel = this.handleQuickGroup(quickGroupItems);
    } catch (error: any) {
      LogUtil.log(`----${this.quickGroupCodeList.codeName}----暂未找到`);
    }
  }

  /**
   * @description 处理快速分组模型动态数据部分(%xxx%)
   * @param {any[]} items
   * @return {*}
   * @memberof AppDEMultiDataViewController
   */
  public handleQuickGroup(items: any[]) {
    if (items.length > 0) {
      const defaultSelect: any = this.getQuickGroupDefaultSelect(items);
      if (defaultSelect) {
        const select = items.find((item: any) => {
          return item.value === defaultSelect.value;
        });
        if (select) select.default = true;
      }
      items.forEach((item: any) => {
        if (item.data && Object.keys(item.data).length > 0) {
          Object.keys(item.data).forEach((name: any) => {
            let value: any = item.data[name];
            if (value && typeof value == 'string' && value.startsWith('%') && value.endsWith('%')) {
              const key = value.substring(1, value.length - 1).toLowerCase();
              if (this.context[key]) {
                value = this.context[key];
              } else if (this.viewParam[key]) {
                value = this.viewParam[key];
              }
            }
            item.data[name] = value;
          });
        }
      });
    }
    return items;
  }

  /**
   * @description 获取快速分组默认选中项
   * @param {any[]} items
   * @return {*}
   * @memberof AppDEMultiDataViewController
   */
  public getQuickGroupDefaultSelect(items: any[]) {
    let defaultSelect: any = null;
    const codeItems: Array<IPSCodeItem> = (this.quickGroupCodeList as IPSAppCodeList).getPSCodeItems() || [];
    if (codeItems.length > 0) {
      for (const item of codeItems) {
        const childItems = item.getPSCodeItems?.() || [];
        if (childItems.length > 0) {
          defaultSelect = childItems.find((_item: any) => {
            return _item.default;
          });
        }
        if (item.default || defaultSelect) {
          defaultSelect = item;
          break;
        }
      }
    }
    if (this.viewParam && this.viewParam['srfitemactivate']) {
      items.forEach((item: any) => {
        if (Object.is(item.value, this.viewParam['srfitemactivate'])) {
          defaultSelect = item;
        }
      });
      delete this.viewParam.srfitemactivate;
    }
    return defaultSelect;
  }

  /**
   * @description 快速搜索
   * @param {string} query
   * @memberof AppDEMultiDataViewController
   */
  public quickSearch(query: string) {
    Object.assign(this.searchParam, { query: query });
    if (this.xDataControlName && this.ctrlRefsMap.get(this.xDataControlName)?.name) {
      this.viewState.next({
        tag: this.ctrlRefsMap.get(this.xDataControlName)?.name,
        action: 'search',
        data: Util.deepCopy(this.searchParam),
      });
    }
  }

  /**
   * @description 快速分组值变化
   * @param {*} event
   * @memberof AppDEMultiDataViewController
   */
  public quickGroupValueChange(event: any) {
    if (event) {
      this.quickGroupParam = event.data;
      if (this.isEmitQuickGroupValue && this.xDataControlName && this.ctrlRefsMap.get(this.xDataControlName)?.name) {
        this.viewState.next({
          tag: this.ctrlRefsMap.get(this.xDataControlName)?.name,
          action: 'search',
          data: Util.deepCopy(this.quickGroupParam),
        });
      }
    }
    this.isEmitQuickGroupValue = true;
  }

  /**
   * @description 部件事件处理
   * @param {string} controlname 部件名称
   * @param {string} action 行为
   * @param {*} data 数据
   * @memberof AppDEMultiDataViewController
   */
  public handleCtrlEvent(controlname: string, action: string, data: any) {
    if (Object.is(controlname, 'quicksearchform') && Object.is(action, MobSearchFormEvents.VALUE_CHANGE)) {
      Object.assign(this.searchParam, data);
      if (this.xDataControlName && this.ctrlRefsMap.get(this.xDataControlName)?.name) {
        this.viewState.next({
          tag: this.ctrlRefsMap.get(this.xDataControlName)?.name,
          action: 'search',
          data: Util.deepCopy(this.searchParam),
        });
      }
    }
    super.handleCtrlEvent(controlname, action, data);
  }
}
